package com.zipeng.service;

import com.zipeng.entity.RegionStats;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: zipeng Li
 * 2021/4/27  9:04
 */
@Slf4j
@Service
public class DataService implements InitializingBean {

    /**
     * 每当程序启动，自动获取一次数据
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        getData();
    }

    private String Data_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private List<RegionStats> list = new ArrayList<>();

    /**
     * 每天凌晨1点执行计划任务，更新list成员变量
     * @throws IOException
     */
    @Scheduled(cron = "${zipeng.Schedules.updateCron}")
    public void getData() throws IOException {
        RequestEntity<Void> requestEntity = RequestEntity.get(Data_URL)
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.8"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();
        if (body == null) {
            return;
        }
        Reader in = new BufferedReader(new InputStreamReader(body.getInputStream()));
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
        for (CSVRecord record : records) {
            RegionStats regionStats = new RegionStats();
            regionStats.setState(record .get("Province/State"));
            regionStats.setCountry(record .get("Country/Region"));
            regionStats.setLatestTotalCases(Integer.parseInt(record.get(record.size()-1)));
            regionStats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
            list.add(regionStats);
        }
        log.info("================数据更新成功===================");
    }

    public List<RegionStats> getList() {
        return list;
    }
}
